<template>
  <div ref="adManager">
    <div :id="gamPath" :name="slot" data-ad-manager="true"></div>
  </div>
</template>

<script setup>
const props = defineProps({
    slotType: {
        type: String,
        required: true
    }
})
const emit = defineEmits(['adSuccess', 'onNullAd'])

const observer = ref(null) // 观察器
const adManager = ref(null) // 广告容器

// 使用 composable 获取 hostname 和 URL 参数
const hostname = useHostname()
// 获取url参数中的channel
const { getParam } = useUrlParams()
const channel = getParam('channel')

const { gamPath, slot } = getGamAdSlot(props.slotType, hostname)
const loadSlotView = (entries) => {
  const entry = entries[0]
  if (entry.isIntersecting) {
    // 上报广告进入视窗事件
    logEvent('GAM_AD_View', { slot: slot });

    // 创建动态加载的 GPT 脚本
    const script = document.createElement('script')
        script.innerHTML = `
          window.googletag = window.googletag || {cmd: []};
          window.googletag.cmd.push(function () {
              window.googletag.defineSlot(
                  "${gamPath}",
                  ['fluid', [window.innerWidth - 40, 300]],
                  "${gamPath}"
              ).addService(window.googletag.pubads());
              window.googletag.pubads().setTargeting('afc_channel', '${channel}');
              window.googletag.pubads().enableSingleRequest();
              window.googletag.pubads().collapseEmptyDivs();
              window.googletag.enableServices();
              window.googletag.display("${gamPath}");
          });
        `

        adManager.value.appendChild(script)
    
    // 停止观察，避免重复触发
    if (observer.value) {
      observer.value.unobserve(adManager.value)
    }
  }
}

onMounted(() => {
  observer.value = new IntersectionObserver(loadSlotView, {
      root: null,
      rootMargin: '88px',
      threshold: 0.05
  })
  observer.value.observe(adManager.value)
})

onUnmounted(() => {
    // 清理观察器
    if (observer.value) {
        observer.value.disconnect()
        observer.value = null
    }
})
</script>

<style scoped>
  
</style>